﻿#include "picturedelegate.h"

#include <QPainter>
#include <QImageReader>

// test
#include <QDebug>

PictureDelegate::PictureDelegate(QObject *parent)
    : QStyledItemDelegate {parent}
{
    QFont font("Microsoft YaHei", 9);
    QFontMetrics metrics(font);
    mContainMargin = metrics.height() * 0.5;
}

void PictureDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QRect rectImage = option.rect;

    QString path = index.data(Qt::DisplayRole).toString();
    QImageReader reader;
    reader.setFileName(path);
    QImage image = reader.read();

    //qDebug() << "paint size "<< option.rect;

    painter->setRenderHint(QPainter::SmoothPixmapTransform);
    painter->drawImage(QRectF(rectImage.x(), rectImage.y(), option.rect.width() - mContainMargin, option.rect.height()), image);

    // 绘制 序号
    QString seq = index.data(Qt::UserRole + 1).toString();
    painter->setPen(Qt::NoPen);
    painter->setBrush(QBrush(QColor(79, 159, 96)));
    QRect rectSeq = QRect(rectImage.x() + mContainMargin, rectImage.y() + mContainMargin, 48, 30);

    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawRoundedRect(rectSeq, mContainMargin, mContainMargin);

    QPen pen;
    pen.setBrush(QBrush(QColor(254, 254, 254)));
    pen.setWidth(2);
    painter->setPen(pen);
    painter->setFont(QFont("Microsoft Yahei", 9, 120));

    painter->setRenderHint(QPainter::TextAntialiasing);
    painter->drawText(rectSeq, Qt::AlignCenter, seq);
}

QSize PictureDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QString path = index.data(Qt::DisplayRole).toString();
    QImageReader reader;
    reader.setFileName(path);

    uint16_t imageWidth = reader.size().width();
    uint16_t imageHeight = reader.size().height();

    int widgetWidth = option.widget->width();
    int widgetHeight = option.widget->height();

    double rate = (double)imageHeight / imageWidth;
    double widthSize = widgetWidth;
    double heightSize = widgetWidth * rate;

    if (widgetHeight < heightSize)
    {
        heightSize = widgetHeight;
        widthSize = heightSize / rate;
    }

    //qDebug() << "size hint " << widthSize << " " << heightSize;

    return QSize(widthSize + mContainMargin, heightSize);
}
